package com.qidian.server.workerThread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import com.qidian.common.Constants;
import com.qidian.server.messages.Message;
import com.qidian.server.messages.plugin2server.NumberTakingMessage;

public class CoreThread extends WorkerThread
{
    private byte[] buffer = null;  
    private DatagramSocket socket = null;  
    private DatagramPacket recvPacket = null;  
    private InetSocketAddress socketAddress = null; 
    public CoreThread(String host, int port, long init_id) throws SocketException
    {
        socketAddress = new InetSocketAddress(host, port);  
        socket = new DatagramSocket(socketAddress);
        buffer = new byte[Constants.socket_buf_size] ;
        recvPacket = new DatagramPacket(buffer,buffer.length) ;
    }

	@Override
	public void init() 
	{
		
	}
    
    /**
     *  消息是否合法
     * 
     * */
    public boolean valid(DatagramPacket packet)
    {
        byte[] data = packet.getData() ;
        Message msg = null ;
        try
        {
            msg = Message.toMessage(data,0,data.length) ;
        }
        catch (Exception e)
        {
            e.printStackTrace() ;
            return false ;
        }
        if (!(msg instanceof NumberTakingMessage))
            return false ;
        return msg.isValid() ;
    }	
	
	@Override
	public void run()
	{
		while(keepRunning)
		{
			try 
			{
				socket.receive(recvPacket) ;
				
				byte[] recvData = recvPacket.getData() ;
				Message msg = Message.toMessage(recvData, 0, recvData.length) ;
				if (msg == null || ! msg.isValid())
					continue ;
				
				
					
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
    
}
